#include "unp.h"
#include <sys/poll.h>

#define SETSIZE 10

int main(int argc, char *argv[])
{
    int listenfd, connfd, addrlen;
    struct sockaddr_in servaddr, cliaddr;
    int i, n, maxi;
    struct pollfd client[SETSIZE];
    char buf[MAXLINE];

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);
    client[0].fd = listenfd;
    client[0].events = POLLIN;
    maxi = 0;

    for (i=1; i<SETSIZE; i++) {
        client[i].fd = -1;
    }

    printf("listenfd=%d\n", listenfd);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    Bind(listenfd, (SA*)&servaddr, sizeof(servaddr));
    Listen(listenfd, 15);


    for (; ;) {
        poll(client, maxi+1, -1);

        if (client[0].revents & POLLIN) {
            addrlen = sizeof(struct sockaddr_in);
            connfd = Accept(listenfd, (SA*)&cliaddr, &addrlen);
            printf("listenfd=%d, connfd=%d\n", listenfd, connfd);
            for (i=0; i<SETSIZE; i++) {
                if (client[i].fd == -1) {
                    client[i].fd = connfd;
                    client[i].events = POLLIN;
                    printf("i=%d, listenfd=%d, connfd=%d\n", i, listenfd, connfd);
                    if (maxi < i) {
                        maxi = i;
                    }
                    break;
                }
            }
        }

        for (i=1; i<=maxi; i++) {
            if (client[i].fd < 0) {
                continue;
            }
            if (client[i].revents & (POLLIN | POLLERR)) {
                if ( (n=read(client[i].fd, buf, sizeof(buf))) < 0) {
                    if (errno == ECONNRESET) {
                        close(client[i].fd);
                        client[i].fd = -1;
                        continue;
                    } else {
                        err_sys("read error");
                    }
                } else if (n == 0) {
                    close(client[i].fd);
                    client[i].fd = -1;
                } else {
                    Writen(client[i].fd, buf, n);
                }
            }
        }
    }
}

